import pygame  # 导入pygame库
import random  # 导入random库，用于生成随机数

# 初始化pygame
pygame.init()

# 定义颜色
WHITE = (255, 255, 255)  # 白色
BLACK = (0, 0, 0)  # 黑色
RED = (255, 0, 0)  # 红色
GREEN = (0, 255, 0)  # 绿色
GRAY = (128, 128, 128)  # 灰色

# 设置游戏窗口
WIDTH = 800  # 窗口宽度
HEIGHT = 600  # 窗口高度
game_window = pygame.display.set_mode((WIDTH, HEIGHT))  # 创建游戏窗口
pygame.display.set_caption('Snake Game')  # 设置窗口标题

# 蛇的初始位置和大小
SNAKE_BLOCK = 20  # 蛇身每个方块的大小
SNAKE_SPEED = 15  # 蛇的移动速度

# 初始化时钟
clock = pygame.time.Clock()  # 创建时钟对象，用于控制游戏帧率

# 定义字体
font = pygame.font.SysFont(None, 50)  # 创建大号字体
small_font = pygame.font.SysFont(None, 35)  # 创建小号字体

def display_score(score):
    # 显示分数
    score_text = font.render(f"Score: {score}", True, WHITE)  # 渲染分数文本
    game_window.blit(score_text, [0, 0])  # 将分数显示在屏幕左上角

def draw_snake(snake_list):
    # 绘制蛇身
    for block in snake_list:
        pygame.draw.rect(game_window, GREEN, [block[0], block[1], SNAKE_BLOCK, SNAKE_BLOCK])  # 绘制蛇身的每个方块

def display_message(msg, color, y_displace=0):
    # 显示消息
    text = font.render(msg, True, color)  # 渲染消息文本
    text_rect = text.get_rect()  # 获取文本矩形
    text_rect.center = (WIDTH / 2, HEIGHT / 2 + y_displace)  # 设置文本位置
    game_window.blit(text, text_rect)  # 将文本显示在屏幕上

def pause_screen():
    # 暂停屏幕
    paused = True
    display_message("Game Paused", WHITE)  # 显示暂停消息
    display_message("Press ESC to continue or Q to quit", WHITE, 50)  # 显示操作提示
    pygame.display.update()  # 更新显示
    
    while paused:
        for event in pygame.event.get():  # 处理事件
            if event.type == pygame.QUIT:  # 如果点击关闭窗口
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:  # 如果按下键盘
                if event.key == pygame.K_ESCAPE:  # 如果按下ESC键
                    paused = False  # 取消暂停
                elif event.key == pygame.K_q:  # 如果按下Q键
                    pygame.quit()
                    quit()
        clock.tick(5)  # 控制帧率

def game_loop():
    # 游戏主循环
    game_over = False  # 游戏是否结束
    game_close = False  # 是否关闭游戏

    x1 = WIDTH / 2  # 蛇头的初始X坐标
    y1 = HEIGHT / 2  # 蛇头的初始Y坐标

    x1_change = 0  # X方向的移动
    y1_change = 0  # Y方向的移动

    snake_list = []  # 蛇身列表
    snake_length = 1  # 蛇的初始长度

    food_x = round(random.randrange(0, WIDTH - SNAKE_BLOCK) / 20.0) * 20.0  # 食物的X坐标
    food_y = round(random.randrange(0, HEIGHT - SNAKE_BLOCK) / 20.0) * 20.0  # 食物的Y坐标

    direction = "RIGHT"  # 蛇的初始方向

    while not game_close:
        while game_over:
            # 游戏结束时的处理
            game_window.fill(BLACK)  # 填充黑色背景
            display_message("Game Over!", RED)  # 显示游戏结束消息
            display_message("Press C-Play Again or Q-Quit", WHITE, 50)  # 显示操作提示
            display_score(snake_length - 1)  # 显示最终分数
            pygame.display.update()  # 更新显示

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return "QUIT"  # 退出游戏
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        return "QUIT"  # 退出游戏
                    if event.key == pygame.K_c:
                        return "PLAY_AGAIN"  # 重新开始游戏

        for event in pygame.event.get():
            # 处理游戏中的事件
            if event.type == pygame.QUIT:
                game_close = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and direction != "RIGHT":
                    direction = "LEFT"
                elif event.key == pygame.K_RIGHT and direction != "LEFT":
                    direction = "RIGHT"
                elif event.key == pygame.K_UP and direction != "DOWN":
                    direction = "UP"
                elif event.key == pygame.K_DOWN and direction != "UP":
                    direction = "DOWN"
                elif event.key == pygame.K_ESCAPE:
                    pause_screen()  # 暂停游戏

        # 根据方向更新蛇的移动
        if direction == "LEFT":
            x1_change = -SNAKE_BLOCK
            y1_change = 0
        elif direction == "RIGHT":
            x1_change = SNAKE_BLOCK
            y1_change = 0
        elif direction == "UP":
            y1_change = -SNAKE_BLOCK
            x1_change = 0
        elif direction == "DOWN":
            y1_change = SNAKE_BLOCK
            x1_change = 0

        # 检查是否撞墙
        if x1 >= WIDTH or x1 < 0 or y1 >= HEIGHT or y1 < 0:
            game_over = True

        # 更新蛇头位置
        x1 += x1_change
        y1 += y1_change
        game_window.fill(BLACK)  # 填充黑色背景
        pygame.draw.rect(game_window, RED, [food_x, food_y, SNAKE_BLOCK, SNAKE_BLOCK])  # 绘制食物
        snake_head = []
        snake_head.append(x1)
        snake_head.append(y1)
        snake_list.append(snake_head)
        if len(snake_list) > snake_length:
            del snake_list[0]  # 删除多余的蛇身

        # 检查是否撞到自己
        for segment in snake_list[:-1]:
            if segment == snake_head:
                game_over = True

        draw_snake(snake_list)  # 绘制蛇
        display_score(snake_length - 1)  # 显示分数

        pygame.display.update()  # 更新显示

        # 检查是否吃到食物
        if x1 == food_x and y1 == food_y:
            food_x = round(random.randrange(0, WIDTH - SNAKE_BLOCK) / 20.0) * 20.0  # 生成新的食物X坐标
            food_y = round(random.randrange(0, HEIGHT - SNAKE_BLOCK) / 20.0) * 20.0  # 生成新的食物Y坐标
            snake_length += 1  # 蛇长度增加

        clock.tick(SNAKE_SPEED)  # 控制游戏速度

    return "QUIT"  # 退出游戏

# 主程序
def main():
    running = True
    while running:
        result = game_loop()  # 运行游戏循环
        if result == "QUIT":
            running = False  # 如果返回QUIT，则退出主循环

    pygame.quit()  # 退出pygame
    quit()  # 退出程序

if __name__ == "__main__":
    main()  # 运行主程序